package net.sourceforge.j2meautonetwork.view;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;

import net.sourceforge.j2meautonetwork.J2meAutoNetworkMIDlet;
import net.sourceforge.j2meautonetwork.operation.NetworkManager;
import net.sourceforge.j2meautonetwork.util.CodeDefine;
/**
 * 日志输出窗体
 * @author Steven King
 * @version 0.1
 */
public class DebugForm extends Form implements CommandListener {

    private static DebugForm instance;

    private int m_log_counter = 0;

    private Displayable backHandle;

    private Command Back = new Command(CodeDefine.BACK_COMMAND_LABLE,
            Command.BACK, 0);
    
    private Command Cancel = new Command(CodeDefine.CANCEL_COMMAND_LABLE,
            Command.OK, 0);
    
    private DebugForm(String title) {
        super(title);
    }

    static {
        instance = new DebugForm(CodeDefine.TEST_LOG_FORM_TITLE_LABLE);
        instance.initSelf();
    }

    public static synchronized DebugForm getDebugForm(Displayable backHandle) {
        instance.backHandle = backHandle;
        J2meAutoNetworkMIDlet.getDisplay().setCurrent(instance);
        return instance;
    }

    private void initSelf() {
        this.addCommand(Back);
        this.addCommand(Cancel);
        this.setCommandListener(this);
    }

    public synchronized void appendLog(String log) {
        m_log_counter++;
        append(log + "\r\n");
    }

    public synchronized void clearLog() {
        for (; m_log_counter >= 0; m_log_counter--)
            delete(m_log_counter);
    }

    public void commandAction(Command command, Displayable display) {
        if (command == Back)
            J2meAutoNetworkMIDlet.getDisplay().setCurrent(
                    backHandle);
        if (command == Cancel)
            NetworkManager.getInstance().cancelTry();
    }

}
